package cicd

import (
	"io/ioutil"
	"strconv"
	"sort"
	"os"
	"fmt"
	"strings"
)

type Output struct {
	Id int				`json:"id"`
	Mdtime string		`json:"mdtime"`
	Path string			`json:"path"`
	Status string		`json:"status"`
}


func ParseOutputDir(pathname string)(result []Output,err error) {
	rd, err := ioutil.ReadDir(pathname)
	var dirnums []int
	for _, f := range rd {
		n,err := strconv.Atoi(f.Name())
		if err == nil {
			dirnums = append(dirnums,n)
		}
	}
	sort.Sort(sort.Reverse(sort.IntSlice(dirnums)))
	for _,id := range dirnums {
		fileinfo,_ := os.Stat(pathname + "/" + strconv.Itoa(id) + "/output.txt")
		o := Output{
			Id: id,
			Mdtime: fileinfo.ModTime().Format("2006-01-02 15:04:05"),
			Path: pathname + "/" + strconv.Itoa(id) + "/output.txt",
		}
		status,err := ioutil.ReadFile(fmt.Sprintf("%s/%d/status",pathname,id))
		if err != nil {
			o.Status = "unknow"
		}else {
			o.Status = strings.TrimSpace(string(status))
		}

		result = append(result,o)
	}

	return
}
